package org.taobao.ibatiside.ui.action;

import java.util.Iterator;

import org.eclipse.core.resources.IWorkspaceRoot;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.ui.IViewActionDelegate;
import org.eclipse.ui.IViewPart;
import org.eclipse.ui.navigator.CommonNavigator;
import org.taobao.ibatiside.core.filemodel.IbatisElement;
import org.taobao.ibatiside.ui.view.BatisCommonViewerMapper;

public class RefreshAllAction implements IViewActionDelegate {
	private ISelection selection;
	private CommonNavigator navigator;
	@Override
	public void run(IAction action) {
		if (navigator == null ) return;
		if (!(selection instanceof IStructuredSelection)) return;
		if (selection == null || selection.isEmpty() || ((IStructuredSelection)selection).getFirstElement() instanceof IWorkspaceRoot){
			navigator.getCommonViewer().refresh();
		}
		
		IStructuredSelection str_sel = (IStructuredSelection) this.selection;
		for (Iterator ite = str_sel.iterator(); ite.hasNext();){
			BatisCommonViewerMapper mapper = (BatisCommonViewerMapper) navigator.getCommonViewer().getMapper();
			IbatisElement ibatisElement = (IbatisElement)ite.next();
			Object element = mapper.getWrapper(ibatisElement.getResource());
			if (element != null){
				navigator.getCommonViewer().refresh(element);
			}
		}
	}

	@Override
	public void selectionChanged(IAction action, ISelection selection) {
		this.selection = selection;
	}

	@Override
	public void init(IViewPart view) {
		navigator = (CommonNavigator) view;
	}

}
